#!/usr/bin/perl
# 2013/09/17 Check the number of total read in each location

use strict;
use warnings;
use IO::File;
use Getopt::Std;
use Carp qw(croak);
$| = 0;

if(@ARGV != 4 or $ARGV[0] eq '--help'){
	die "Usage : $0 -i [map file] -o [output file]\n";
}

my %opt;
getopts("i:o:", \%opt);
my $FILE_map = $opt{i};
my $FILE_out = $opt{o};



# id chr1 loc1 direction1 quality1 hind1 hiv 2nd_loc1 chr2 loc2 direction2 quality2 hind2 hind_loc2 type(unique or repeat) number(alignable locations) locations
my %data;
my $fh_map = IO::File->new($FILE_map) or die "cannot open $FILE_map: $!";
while($_ = $fh_map->getline()){
	s/\r?\n//;
	my ($id, $chr1, $loc1, $direction1, $mapQ1, $hinID1, $hinLoc1, $chr2, $loc2, $direction2, $mapQ2, $hinID2, $hinLoc2, $type, $num, $locations) = split /\t/;
	$data{$hinID1}++;
	$data{$hinID2}++;
}
$fh_map->close();


my $fh_out = IO::File->new($FILE_out, 'w') or die "cannot write $FILE_out: $!";
$fh_out->print("#rank\thinID\tnumber\n");
my $rank = 1;
foreach my $k (sort {$data{$a} <=> $data{$b}} keys %data){
	 $fh_out->print("$rank\t$k\t$data{$k}\n");
	 $rank++;
}
$fh_out->close();
